import { BaseEnvMirror } from "@/modules/dev-env/mirror/mirror.ts";
import { MirrorDataFilter } from "@/modules/dev-env/mirror/filter.ts";
import type { ResourceVersionResponse, ToolInstallVersionItem } from "@/modules/dev-env/common/types.ts";
import path from "@/framework/util/path.ts";
import { getCustomResourceUrl } from "@/modules/dev-env/common/resource.ts";

export class MysqlLatestMirror extends BaseEnvMirror {
  constructor() {
    super({
      id: "mysql.latest",
      name: "最新版",
      url: getCustomResourceUrl("/data/mysql-latest.json"),
      website: "https://dev.mysql.com/",
    });
  }

  async getDownloadList(query: Record<string, any>): Promise<ToolInstallVersionItem[]> {
    const resp = await native.http.getJson<ResourceVersionResponse>(this.url);
    return resp.data.versions.map(it => ({
      id: `mysql-${it.version}`,
      version: it.version,
      name: path.basename(it.url),
      url: it.url,
    }));
  }
}

class MySQLVersionFilter extends MirrorDataFilter {
  constructor() {
    super("版本");
  }

  protected filter0(versions: ToolInstallVersionItem[]): ToolInstallVersionItem[] {
    return versions.filter(it => it.version1 === this.value);
  }
}

export class MysqlHistoryMirror extends BaseEnvMirror {
  private readonly _versionFilter = new MySQLVersionFilter();

  constructor() {
    super({
      id: "mysql.history",
      name: "历史版本",
      url: getCustomResourceUrl("/data/mysql-history.json"),
      website: "https://dev.mysql.com/",
    });
  }

  protected getFilters0(): MirrorDataFilter[] {
    return [this._versionFilter];
  }

  async getDownloadList(query: Record<string, any>): Promise<ToolInstallVersionItem[]> {
    const resp = await native.http.getJson<ResourceVersionResponse>(this.url);
    const majorVersions = new Set<string>();
    const versions = resp.data.versions.map<ToolInstallVersionItem>(it => {
      const [major] = it.version.split(".");
      majorVersions.add(major);
      return {
        id: `mysql-${it.version}`,
        version: it.version,
        name: path.basename(it.url),
        url: it.url,
        version1: major,
      };
    });

    const majorVersionValues = [...majorVersions];
    this._versionFilter.value = majorVersionValues[0];
    this._versionFilter.setDataSource(majorVersionValues.map(it => ({ value: it })));

    return versions;
  }
}
